//
//  YZMSuggestionListViewController.m
//  YZMicroStock
//
//  Created by wangminhong on 16/4/5.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMSuggestionListViewController.h"
#import "YZMResultView.h"
#import "YZMSuggestionListCell.h"
#import "YZMSuggestionListNoneCell.h"
#import "YZMAppHelper.h"
#import "YZClient.h"
#import "YZMPageService.h"
#import "YZMSuggestionListModel.h"
#import "YZMSuggestionModel.h"
#import "YZMSuggestionService.h"
#import <BlocksKit/UIControl+BlocksKit.h>

#import <MJRefresh/MJRefresh.h>

static NSString *const sYZMSuggestionListCell = @"YZMSuggestionListCell";
static NSString *const sYZMSuggestionListNoneCell = @"YZMSuggestionListNoneCell";
@interface YZMSuggestionListViewController()<UITableViewDelegate, UITableViewDataSource>

@end

@implementation YZMSuggestionListViewController{
    
    UITableView *_tableView;
    NSMutableArray *_dataSource;
    
    YZMPageService *_pageService;
    MJRefreshNormalHeader *_refreshHeader;
    MJRefreshAutoNormalFooter *_refreshFooter;
    YZMResultView *_resultView;
    NSArray *_questionList;
}

- (id)init{
    
    self = [super init];
    
    if (self) {
        
        self.hidesBottomBarWhenPushed = YES;
        _dataSource = [NSMutableArray array];
        _pageService = [YZMPageService new];
    }
    
    return self;
}

- (void)viewDidLoad{
    
    [super viewDidLoad];
    self.view.backgroundColor = [YZMAppStyle appBackgroundColor];
    self.navigationItem.rightBarButtonItem = [YZMAppStyle rightBarItemWithImage:@"icon_white_tel" target:self action:@selector(rightBarButtonItem)];
    self.title = @"提问";
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(fetchSuggestionListFirstPage) name:sYZMSuggestionListDidUpdateNotification object:nil];
    
    [self createObjects];
    if ([YZMUserService sharedService].currentUser) {
        
        [self fetchSuggestionListFirstPage];
    }
}

#pragma mark -- Network Request

- (void)fetchSuggestionListFirstPage{
    
    [_pageService preChangeWithPage:_pageService.minPage andTimeEnd:YES];
    [self fetchSuggestionList];
}

- (void)fetchSuggestionListNextPage{
    
    [_pageService preChangeWithPage:_pageService.nextPage  andTimeEnd:YES];
    [self fetchSuggestionList];
}

- (void)endRefresh{
    
    if (_refreshHeader.isRefreshing) {
        
        [_refreshHeader endRefreshing];
    }
    
    if (_refreshFooter.isRefreshing) {
        
        [_refreshFooter endRefreshing];
    }
}

- (void)fetchSuggestionList{
    
    /*无网处理*/
    if (kNetworkNotReachability) {
        
        [self endRefresh];
        
        if (!_dataSource || _dataSource.count == 0) {
            
            _resultView.status = YZM_RESULT_STATUS_FOR_NO_WIFI;
            _tableView.mj_header = nil;
            _tableView.mj_footer = nil;
            _tableView.hidden = YES;
            
        }else{
            
            [NSError yz_showMessageForNoWifi];
        }
        
        return;
    }
    
    if ((!_dataSource || _dataSource.count == 0) && _tableView.hidden) {
        
        _resultView.status = YZM_RESULT_STATUS_FOR_LOADING;
    }
    
    [YZClient fetchSuggestionListWithPage:_pageService.tempPage
                              andPageSize:_pageService.pageSize
                               andEndTime:_pageService.tempTimeEnd
                                  success:^(NSURLResponse *response, id responseObject){
        
        [self endRefresh];
        
        _tableView.mj_header = _refreshHeader;
        _tableView.mj_footer = _refreshFooter;
        _resultView.status = YZM_RESULT_STATUS_FOR_NORMAL;
        _tableView.hidden = NO;
        
        YZGeneralResultModel *topModel = responseObject;
                                      
        if (topModel.success) {
            
            YZMSuggestionListModel *result = topModel.data;
            
            NSArray *sList = result.items;
            NSInteger pageIndex = result.currentPage;
            
            if (pageIndex == _pageService.minPage) {
                
                [_dataSource removeAllObjects];
                [_dataSource addObjectsFromArray:sList];
                
            }else{
                
                [_dataSource addObjectsFromArray:sList];
            }
            
            if (result.currentPage >= result.totalPage) {
                _refreshFooter.state = MJRefreshStateNoMoreData;
                
            }else{
                
                _refreshFooter.state = MJRefreshStateIdle;
            }
            [_tableView reloadData];
            [_pageService effectChange];
        }
        else
        {
            if (!_dataSource || _dataSource.count == 0) {
                
                [_resultView syncStatusWithError:[NSError yz_errorWithMessage:topModel.resultMessage]];
                _tableView.mj_header = nil;
                _tableView.mj_footer = nil;
                _tableView.hidden = YES;
                
            }else{
                
                [topModel showMessage];
            }
        }
    } failure:^(NSError *error){
        
        [self endRefresh];
        
        //网络异常处理
        if (!_dataSource || _dataSource.count == 0) {
            
            [_resultView syncStatusWithError:error];
            _tableView.mj_header = nil;
            _tableView.mj_footer = nil;
            _tableView.hidden = YES;
            
        }else{
        
            [error yz_showMessage];
        }
    }];
}

#pragma mark TableView DataSource

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (_dataSource.count == 0) {
        
        YZMSuggestionListNoneCell *cell = [tableView dequeueReusableCellWithIdentifier:sYZMSuggestionListNoneCell forIndexPath:indexPath];
        
        return cell;
    }
    
    YZMSuggestionListCell *cell = [tableView dequeueReusableCellWithIdentifier:sYZMSuggestionListCell forIndexPath:indexPath];
    
    YZMSuggestionModel *instance = _dataSource[indexPath.section];
    cell.record = instance;
    
    return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return _dataSource.count?_dataSource.count:1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
}

#pragma mark -- UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (_dataSource.count != 0) {
        
        return [YZMSuggestionListCell heightForRecord:_dataSource[indexPath.section]];
    }
    
    return _tableView.frame.size.height;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 10.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    return [UIView new];
}


#pragma mark -- Event Response

- (void)rightBarButtonItem{
    
    [YZMAppHelper callServicePhone];
}


#pragma mark -- Private Method

- (void)createObjects{
    
    UIButton *submitButton = [YZMAppStyle submitButton];
    submitButton.enabled = YES;
    submitButton.backgroundColor = [UIColor whiteColor];
    [submitButton setTitle:@"我要留言" forState:UIControlStateNormal];
    [submitButton setTitleColor:[YZMAppStyle colorForRiseText] forState:UIControlStateNormal];
    [self.view addSubview:submitButton];
    [submitButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
    }];
    [submitButton bk_addEventHandler:^(id sender) {
        [YZMHCMInstance pushViewControllerWithName:@"YZMSuggestionSubmitViewController" andParams:nil];
    } forControlEvents:UIControlEventTouchUpInside];
    
    _tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    [_tableView registerClass:[YZMSuggestionListCell class] forCellReuseIdentifier:sYZMSuggestionListCell];
    [_tableView registerClass:[YZMSuggestionListNoneCell class] forCellReuseIdentifier:sYZMSuggestionListNoneCell];
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.backgroundView = nil;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.dataSource = self;
    _tableView.delegate = self;
    
    [self.view addSubview:_tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *maker){
        
        maker.top.equalTo(self.view).offset(15);
        maker.left.right.equalTo(self.view);
        maker.bottom.equalTo(submitButton.mas_top).offset(-10);
    }];
    
    _refreshHeader = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self fetchSuggestionListFirstPage];
    }];
    
    [_refreshHeader setTitle:@"下拉可以刷新" forState:MJRefreshStateIdle];
    [_refreshHeader setTitle:@"正在刷新数据" forState:MJRefreshStateRefreshing];
    _refreshHeader.stateLabel.textColor = [YZMAppStyle colorForGrayText];
    _refreshHeader.stateLabel.font = [YZMAppStyle mediumSizeFont];
    _refreshHeader.lastUpdatedTimeLabel.hidden = YES;
    
    _tableView.mj_header = _refreshHeader;
    
    _refreshFooter = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self fetchSuggestionListNextPage];
    }];
    [_refreshFooter setTitle:@"上拉加载更多" forState:MJRefreshStateIdle];
    [_refreshFooter setTitle:@"正在加载更多数据" forState:MJRefreshStateRefreshing];
    
    _refreshFooter.stateLabel.textColor = [YZMAppStyle colorForGrayText];
    _refreshFooter.stateLabel.font = [YZMAppStyle mediumSizeFont];
    
    _tableView.mj_footer = _refreshFooter;
    
    _resultView = [YZMResultView new];
    [self.view addSubview:_resultView];
    [_resultView mas_makeConstraints:^(MASConstraintMaker *maker){
        
        maker.left.right.equalTo(self.view);
        maker.centerY.equalTo(self.view);
    }];
    
    _resultView.status = YZM_RESULT_STATUS_FOR_NORMAL;
}


@end
